import 'package:animation_effect_demo/src/effects/image_effect/static_image_animation_effect.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../base/christmas_light_style.dart';
import '../effects/base/base_effect.dart';
import '../effects/effect_template.dart';
import '../widget/button.dart';
import '../widget/check_box.dart';
import '../widget/dialog.dart';
import '../widget/fixed_animation_container.dart';
import '../widget/template_settings.dart';

class EditTemplatePage extends StatefulWidget{
  final BaseEffect baseEffect;

  final EffectOperation? operation;

  const EditTemplatePage({Key? key,required this.baseEffect,this.operation}) : super(key: key);
  @override
  State<EditTemplatePage> createState() => _EditTemplatePageState();

}

class _EditTemplatePageState extends State<EditTemplatePage>{
  EffectOperation? operation;
  bool enableSpeed = false;
  RangeArgument? speedRange;
  bool enableAngle = false;
  RangeArgument? angleRange;
  bool enableDensity = false;
  RangeArgument? densityRange;
  bool enableColorWidth = false;
  RangeArgument? colorWidthRange;
  bool isFixedColorCount = false;
  RangeArgument? colorCountRange;
  List<Color>? colorList;
  bool enableEditColor = false;
  DynamicType? dynamicType;
  bool isFavorite = false;
  SpeedOrientation? speedOrientation;
  late List<List<Color>> colorTemplateList;

  @override
  void initState() {
    BaseEffect baseEffect = widget.baseEffect;
    operation = widget.operation?.copyWith();
    if (baseEffect is EditableAnimationEffect) {
      enableSpeed = baseEffect.enableSpeed;
      if(enableSpeed){
        speedRange = baseEffect.speedRange;
      }
      enableSpeed = enableSpeed;

      enableAngle = baseEffect.enableAngle;
      if(enableAngle){
        angleRange = baseEffect.angleRange;
      }
      enableAngle = enableAngle;

      enableDensity = baseEffect.enableDensity;
      if(enableDensity){
        densityRange = baseEffect.densityRange;
      }
      enableDensity = enableDensity;

      enableColorWidth = baseEffect.enableColorWidth;
      if(enableColorWidth){
        colorWidthRange = baseEffect.colorWidthRange;
      }
      enableColorWidth = enableColorWidth;

      isFixedColorCount = baseEffect.isFixedColorCount;
      if(!isFixedColorCount){
        colorCountRange = baseEffect.colorCountRange;
      }

      colorList = baseEffect.getColorList(effectOperation: operation);
      colorTemplateList = [colorList!];
      enableEditColor = baseEffect.enableEditColor;

    }
    super.initState();
  }


  Future<void> _onEditClick() async {
    int? speed;
    if (enableSpeed) {
      speed = operation?.speed ?? speedRange!.defaultValue;
    }

    int? angle;
    if (enableAngle) {
      angle = operation?.angle ?? angleRange!.defaultValue;
    }
    int? colorWidth;
    if (enableColorWidth) {
      colorWidth = operation?.colorWidth ??
          colorWidthRange!.defaultValue;
    }

    int? density;
    if (enableDensity) {
      density =
          operation?.density ?? densityRange!.defaultValue;
    }

    int selectedIndex = operation?.colorIndex ?? 0;


    // bool enableEditColor = enableEditColor;

    print('${widget.baseEffect.effectTyp}+++++speed:$speed');

    var result = await showDialog(
        context: context,
        builder: (context) {
          return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return ChristmasLightDialog(
                actions: [
                  TextButton(
                      onPressed: () => Navigator.of(context).pop(),
                      child: Text(
                        '取消',
                        style: TextStyle(color: Colors.grey),
                      )),
                  TextButton(
                      onPressed: () async {
                        Navigator.of(context).pop(true);
                      },
                      child: Text(
                        '保存',
                        style: TextStyle(color: christmasLightStyle.primaryColor),
                      )),
                ],
                child: Padding(
                  padding:
                  const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                  child: TemplateSettings(
                    speed: speed,
                    speedRange: speedRange,
                    colorList: colorList,
                    colorCountRange: colorCountRange,
                    colorTemplateList: colorTemplateList,
                    density: density,
                    densityRange: densityRange,
                    colorWidth: colorWidth,
                    colorWidthRange: colorWidthRange,
                    enableEditColor: enableEditColor,
                    // directionIndex: directionIndex,
                    speedOrientation: speedOrientation,
                    templateIndex: selectedIndex,
                    angle: angle,
                    isFixedColorCount: isFixedColorCount,
                    angleRange: angleRange,
                    onAddColor: (List<Color>? colors) {
                      if (colors == null) {
                        return;
                      }
                      setState(() {
                        colorTemplateList.add(colors);
                        selectedIndex = colorTemplateList.length-1;
                      });
                    },
                    onTemplateSelect: (index) {
                      setState(() {
                        selectedIndex = index;
                      });
                    },
                    onRemoveTemplate: (index) {
                      setState(() {
                        colorTemplateList.removeAt(index);
                        if (selectedIndex > colorTemplateList.length - 1) {
                          selectedIndex = colorTemplateList.length - 1;
                        }
                      });
                    },
                    onAngleChanged: (value){
                      setState((){
                        angle = value;
                      });
                    },
                    onSpeedChanged: (value){
                      setState((){
                        speed = value.toInt();
                      });
                    },
                    onDensityChanged: (value){
                      setState((){
                        density = value.toInt();
                      });
                    },
                    onColorWidthChanged: (value){
                      setState((){
                        colorWidth = value.toInt();
                      });
                    },
                    onDirectionChanged: (value){
                      setState((){
                        speedOrientation = value;
                      });
                    },
                  ),
                ),
              );
            },
          );
        });

    if (result == true) {

      List<Color>? newColorList = colorTemplateList[selectedIndex];

      ///新建的模板没有颜色模板列表，所以colorIndex = 0;
      EffectOperation newOperation = EffectOperation(
          colorList: newColorList,
          colorIndex: 0,
          speed: speed,
          angle: angle,
          colorWidth: colorWidth,
          density: density,
          speedOrientation: speedOrientation);


      newOperation.colorIndex = selectedIndex;
      setState(() {
        operation = newOperation;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Expanded(
              flex: 5,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: FixedAnimationContainer(
                  widget.baseEffect,
                  operation: operation,
                ),
              )),
          Expanded(
            flex: 2,
            child: Column(
              children: [
                Visibility(
                  visible: widget.baseEffect is EditableAnimationEffect,
                  child: GestureDetector(
                    onTap: _onEditClick,
                    child: Container(
                      margin: const EdgeInsets.all(20.0),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(6.0),
                          border: Border.all(color: Colors.white.withAlpha(40))),
                      child: const Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Icon(Icons.edit),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding:
                  const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                  child: Row(
                    children: [
                      ChristmasLightFavoriteCheckBox(
                        value: isFavorite,
                        onChanged: (value) => setState(() {
                          isFavorite = value;
                        })),
                      SizedBox(
                        width: 14,
                      ),
                      Expanded(
                        child: ChristmasLightPositiveButton(
                          child: const Text('应用'),
                          onPressed: () {},
                        ),
                      ),
                      SizedBox(
                        width: 44,
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

}